import { cn } from "@/lib/utils"
import { ChevronsLeft, MenuIcon, Plus, PlusCircle, Search, Settings, Trash } from "lucide-react"
import { useParams, usePathname, useRouter } from "next/navigation"
import { ElementRef, useEffect, useRef, useState } from "react"
import { useMediaQuery } from "usehooks-ts"
import { UserItem } from "./user-item"
import { useMutation } from "convex/react"
import { api } from "@/convex/_generated/api"
import { Item } from "./item"
import { toast } from "sonner"
import { DocumentList } from "./document-list"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { TrashBox } from "./trash-box"
import { useSearch } from "@/hooks/use-search"
import { useSettings } from "@/hooks/use-settings"
import { NavBar } from "./navbar"

export const Navigation = () => {
    // 路由
    const router = useRouter()
    // 设置的控制
    const settings = useSettings()
    // 是否是移动端
    const isMobile = useMediaQuery('(max-width: 414px)')
    // 是否是重置大小 用于拖拽
    const isResizingRef = useRef(false)
    // 侧边栏
    const sidebarRef = useRef<ElementRef<"aside">>(null)
    // 导航图标
    const navbarRef = useRef<ElementRef<"div">>(null)
    // 是否重置，用于过度动画
    const [isReseting, setIsReseting] = useState(false)
    // 是否折叠
    const [isCollapsed, setIsCollapsed] = useState(false)
    // 路由地址
    const pathname = usePathname()
    // 路由参数
    const params = useParams()
    // 新增
    const create = useMutation(api.documents.create)
    // search
    const { onOpen } = useSearch()

    useEffect(() => {
        if (isMobile) {
            collapse()
        } else {
            resetWidth()
        }
    }, [isMobile])

    useEffect(() => {
        if (isMobile) {
            collapse()
        }
    }, [pathname, isMobile])



    const handleMouseDown = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        event.preventDefault()
        event.stopPropagation()
        isResizingRef.current = true
        document.addEventListener("mousemove", handleMouseMove)
        document.addEventListener("mouseup", handleMouseUp)
    }
    const handleMouseMove = (event: MouseEvent) => {
        if (!isResizingRef.current) return
        let newWidth = event.clientX
        if (newWidth < 240) newWidth = 240
        if (newWidth > 480) newWidth = 480
        if (sidebarRef.current && navbarRef.current) {
            sidebarRef.current.style.width = `${newWidth}px`
            navbarRef.current.style.setProperty("left", `${newWidth}px`)
            navbarRef.current.style.setProperty("width", `calc(100% - ${newWidth}px)`)
        }
    }
    const handleMouseUp = (_: MouseEvent) => {
        isResizingRef.current = false
        document.removeEventListener("mousemove", handleMouseMove)
        document.removeEventListener("mouseup", handleMouseUp)
    }
    /**
    * 拖拽菜单栏
    */
    const resetWidth = () => {
        if (sidebarRef.current && navbarRef.current) {
            setIsCollapsed(false)
            setIsReseting(true)
            sidebarRef.current.style.width = isMobile ? "100%" : "240px"
            navbarRef.current.style.setProperty("left", isMobile ? "100%" : `240px`)
            navbarRef.current.style.setProperty("width", isMobile ? "0" : `calc(100% - 240px)`)
            setTimeout(() => setIsReseting(false), 300);
        }
    }
    /**
    * 折叠菜单栏
    */
    const collapse = () => {
        if (sidebarRef.current && navbarRef.current) {
            setIsCollapsed(true)
            setIsReseting(true)
            sidebarRef.current.style.width = "0"
            navbarRef.current.style.setProperty("left", "0")
            navbarRef.current.style.setProperty("width", "100%")
            setTimeout(() => setIsReseting(false), 300);
        }
    }

    /**
     * 创建
     */
    const handleCreate = () => {
        const promise = create({ title: "Untitled" })
            .then((documentId) => router.push(`/documents/${documentId}`))
        toast.promise(promise, {
            loading: "Creating a new note...",
            success: "New note created!",
            error: "Failed to create a new note."
        })
    }

    return (<>
        <aside ref={sidebarRef} className={
            cn("group/sidebar h-full bg-secondary overflow-y-auto relative flex w-60 flex-col z-[99999]",
                isReseting && "transition-all ease-in-out duration-300",
                isMobile && "w-0"
            )
        }>
            <div role="button" onClick={collapse} className={
                cn("h-6 w-6 text-muted-foreground rounded-sm hover:bg-neutral-300 dark:hover:bg-neutral-600 absolute top-3 right-2 opacity-0 group-hover/sidebar:opacity-100",
                    isMobile && !isCollapsed && "opacity-100")
            }>
                <ChevronsLeft className="h-6 w-6" />
            </div>
            <div>
                <UserItem />
                <Item onClick={onOpen}
                    label="Search"
                    icon={Search}
                    isSearch
                />
                <Item onClick={settings.onOpen}
                    label="Settings"
                    icon={Settings}
                />
                <Item onClick={handleCreate}
                    label="New Page"
                    icon={PlusCircle}
                />
            </div>
            <div className="mt-4">
                <DocumentList />
                <Item onClick={handleCreate}
                    label="Add a page"
                    icon={Plus}
                />
                <Popover >
                    <PopoverTrigger className="w-full">
                        <Item
                            label="Trash"
                            icon={Trash}
                        />
                    </PopoverTrigger>
                    <PopoverContent
                        className="p-0 w-72"
                        side={isMobile ? 'bottom' : 'right'}>
                        <TrashBox />
                    </PopoverContent>
                </Popover>
            </div>
            <div onClick={resetWidth} onMouseDown={handleMouseDown} className="opacity-0 group-hover/sidebar:opacity-100 transition
            cursor-ew-resize absolute h-full w-1 bg-primary/10 right-0 top-0" />
        </aside>
        <div ref={navbarRef} className={
            cn("absolute top-0 left-60  z-[99999] w-[calc(100% - 240px)]",
                isReseting && "transition-all ease-in-out duration-300",
                isMobile && "left-0 w-full"
            )
        }>
            {!!params.documentId ? (<NavBar isCollapsed={isCollapsed} onResetWidth={resetWidth} />) : (<nav>
                {isCollapsed && <MenuIcon onClick={resetWidth} role="button" className="h-6 w-6 text-muted-foreground" />}
            </nav>)}
        </div>
    </>)
}